package com.example.advice;

import java.io.PrintWriter;
import java.io.StringWriter;

import org.springframework.context.annotation.Lazy;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.example.model.ActionResult;
import com.example.model.ActionResult.ActionResultBuilder;

import lombok.extern.slf4j.Slf4j;

/**
 * ClassName: ExceptionHandlerAdvice 
 * Function: 异常处理
 * Reason:	封装应用返回的异常，将应用的异常转换成对用户友好的消息结果
 * 
 * date: 2017年8月22日 下午7:24:04
 * 
 * @author huangligui
 */
@Lazy
@Slf4j
@ControllerAdvice
public class ExceptionHandlerAdvice {


	@ExceptionHandler(value = Exception.class)
	public ResponseEntity<ActionResult<String>> handleException(Exception e) {
		log.error(e.getMessage(), e);
		ActionResultBuilder<String> result = ActionResult.serverError();
		result.withMsg(e.getMessage());
		result.withData(this.getStackTrace(e));
		return ResponseEntity.ok(result.build());
	}
	
	private String getStackTrace(Exception e) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		return sw.toString();
	}

}
